<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Model\DoctorInfo;
use App\Model\User;
use Hyperf\WebSocketServer\Context;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Exception\WebsocketException;

class WebSocketAuthMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 伪代码，通过 isAuth 方法拦截握手请求并实现权限检查
        if (! $this->isAuth($request)) {
            throw new WebsocketException(401, 'auth faild');
        }
        return $handler->handle($request);
    }

    public function isAuth($request)
    {
        $params = $request->getQueryParams();
        if (!isset($params['token'])) {
            return false;
        }
        $user = User::query()
            ->where('user_token', (string)$params['token'])
            ->first();
        if (!$user)
            return false;
        $request = Context::get(ServerRequestInterface::class);
        $request = $request->withAttribute('user', $user);
        Context::set(ServerRequestInterface::class, $request);
        return true;
    }
}
